package org.amse.ys.sndeditor.model.filesearcher;

import java.io.File;
import java.util.Collection;
import java.util.LinkedList;
import java.util.TreeSet;
import org.amse.ys.sndeditor.model.ISoundFileDescription;

public class FileSearcher /* implements IFileSearcher */{
	public final static String[] SUPPORTED_TYPES = { ".wav" };
	public final static String[] SOURCES_FOR_SEARCH = { "/sdcard" };
	static TreeSet<ISoundFileDescription> myListOfFiles = null;

	synchronized static public void findSupportedFiles() {
		if (myListOfFiles == null) {
			findAgainSupportedFiles();
		}
	}

	synchronized public static Collection<ISoundFileDescription> giveSupportedFiles() {
		// we use only once this collection, thus it is not necessary to create
		// non-modifiable collection

		if (myListOfFiles == null) {
			FileSearcher.findSupportedFiles();
		}
		return myListOfFiles;
	}

	public static boolean supportedFile(File file) {

		String name = file.getName();
		final int last = name.length() - 1;

		for (int i = 0; i < SUPPORTED_TYPES.length; i++) {
			final int currentLast = SUPPORTED_TYPES[i].length() - 1;
			if (name.charAt(last) == SUPPORTED_TYPES[i].charAt(currentLast)) {
				boolean flag = true;
				for (int j = 0; j <= currentLast; j++) {
					if (name.charAt(last - j) != SUPPORTED_TYPES[i]
							.charAt(currentLast - j)) {
						flag = false;
					}
				}
				if (flag) {
					return true;
				}
			}
		}
		return false;
	}

	synchronized public static void findAgainSupportedFiles() {
		myListOfFiles = new TreeSet<ISoundFileDescription>();
		LinkedList<File> stack = new LinkedList<File>();

		for (int i = 0; i < SOURCES_FOR_SEARCH.length; i++) {
			stack.add(new File(SOURCES_FOR_SEARCH[i]));
		}
		// we look through all the paths
		while (!stack.isEmpty()) {
			File pathToProceed = stack.removeFirst();
			File[] fileList = pathToProceed.listFiles();
			// take every file from a path
			for (File tmpFile : fileList) {
				// if it is a path, push it to stack
				if (tmpFile.isDirectory()) {
					stack.add(tmpFile);
				} else if (supportedFile(tmpFile)) {
					// if it is the file we are looking for
					ISoundFileDescription desc = new SoundFileDescription();
					desc.setFile(tmpFile);
					myListOfFiles.add(desc);
				}
			}
		}

	}

}
